package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import jsyf.oa.dao.system.ProvinceDao;
import jsyf.oa.facade.system.ProvinceFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lenovo on 2017/12/9.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class ProvinceService implements ProvinceFacade {
    @Autowired
    private ProvinceDao dao;
    @Override
    public List<JSONObject> getTreeNodes() {
        List<JSONObject> nodeList = new ArrayList<>();
        JSONObject nodeRoot = new JSONObject();
        nodeRoot.put("id","0");
        nodeRoot.put("pId","-1");
        nodeRoot.put("name","行政区域");
        nodeRoot.put("type","root");
        nodeRoot.put("dataId","0");
        nodeRoot.put("isParent",true);
        nodeRoot.put("open",true);
        nodeList.add(nodeRoot);

        List<JSONObject> list = dao.getJSONListByCondition("",new Object[]{});
        for (int i = 0; i < list.size(); i++) {
            JSONObject node = list.get(i);
            if(StringUtils.isEmpty(node.getString("parentId")) || "0".equals(node.getString("parentId"))){
                node.put("pId","0");
            }else{
                node.put("pId",node.getString("parentId"));
            }
            node.put("type","province");
            node.put("dataId",node.getString("id"));
            nodeList.add(node);
        }
        return nodeList;
    }

    @Override
    public List<JSONObject> getProvinceByParentId(String parentId) {
        List<JSONObject> nodeList = new ArrayList<>();
        StringBuffer condition = new StringBuffer();
        Object[] sqlArgs=new Object[1];
        if(!StringUtils.isEmpty(parentId)) {
            condition.append(" AND PARENT_ID=? ");
            sqlArgs[0]=parentId;
        }
        List<JSONObject> list = dao.getJSONListByCondition(condition.toString(),sqlArgs);
        for (int i = 0; i < list.size(); i++) {
            JSONObject node = list.get(i);
            if(StringUtils.isEmpty(node.getString("parentId")) || "0".equals(node.getString("parentId"))){
                node.put("pId","0");
            }else{
                node.put("pId",node.getString("parentId"));
            }
            node.put("type","province");
            node.put("dataId",node.getString("id"));
            nodeList.add(node);
        }
        return nodeList;
    }
}
